#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "formtargettest.h"
#include "formGDBServer.h"

#include <QtSerialPort/QSerialPortInfo>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    on_comname_activated("刷新");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showMsg(int type, QString msg)
{
    switch (type)
    {
    case 0:
    {
        ui->logdis->appendPlainText(msg);
    }break;
    }
}

void MainWindow::showLog(QString msg)
{
    showMsg(0, msg);
}

void MainWindow::on_pbTest_clicked()
{
    QString mode = ui->testmode->currentText();
    QWidget *w = wmap[mode];
    QString comname;
    QString combd;

    comname = ui->comname->currentText();
    if (comname == "刷新")
    {
        showLog("no COM dev");
        return;
    }

    combd = ui->combd->text();
    if (combd.toUInt() == 0)
    {
        showLog("error baud");
        return;
    }

    comname = comname.split(" ").first();

    if (mode == "targetTest")
    {
        formTargetTest *f = static_cast<formTargetTest *>(w);

        delete wmap.take("gdbServer");
        if (w == nullptr)
        {
            f = new formTargetTest;

            f->setParam(comname + ":" + combd);
            wmap[mode] = f;
            connect(f, SIGNAL(outLog(QString)), this, SLOT(showLog(QString)));
            f->setParent(ui->test);
        }

        f->show();
    }

    if (mode == "gdbServer")
    {
        formGDBServer *f = static_cast<formGDBServer *>(w);

        delete wmap.take("targetTest");
        if (w == nullptr)
        {
            f = new formGDBServer;

            f->setParam(comname + ":" + combd);
            wmap[mode] = f;
            connect(f, SIGNAL(outLog(QString)), this, SLOT(showLog(QString)));
            f->setParent(ui->test);
        }

        f->show();
    }
}

void MainWindow::on_comname_activated(const QString &arg1)
{
    if (arg1 != "刷新")
        return;

    ui->comname->clear();
    ui->comname->addItem("刷新");

    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QString name;
        QString desc = info.description();

        name = info.portName() + " " + desc;
        ui->comname->addItem(name);
    }

    if (ui->comname->count() > 1)
    {
        ui->comname->setCurrentIndex(1);
    }
}
